callback('Unable to connect to Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
callback('Unable to find that address.');
} else if (body.status === 'OK') {
callback(undefined, {
address: body.results[0].formatted_address,
latitude: body.results[0].geometry.location.lat,
longitude: body.results[0].geometry.location.lng
});
}
});
};
module.exports.geocodeAddress = geocodeAddress;
All of the complex logic in the geocodeAddress function does indeed need to
happen, but the app.js file doesn't need to worry about it. The geocode.geocodeAddress
function in the app.js file has a very simple if statement that checks whether
there's an error. If there is an error, we will print a message, and if there's not, we
move on. The same thing will be true with promises.
The new Promise callback function will get called with two arguments, resolve and
reject:
var somePromise = new Promise((resolve, reject) => {
});
This is how we'll manage the state of our promise. When we make a promise,
we're making a promise; we're saying, "Hey, I'll go off and I'll fetch that website
data for you." Now this could go well, in which case, you will resolve the
promise, setting its state to fulfilled. When a promise is fulfilled, it's gone out
and it's done the thing you've expected it to do. This could be a database request,
an HTTP request, or something else completely.
Now when you call reject, you're saying, "Hey, we tried to get that thing done
man, but we just could not." So the promise has been considered rejected. These
are the two states that you can set a promise to—fulfilled or rejected. Just like
inside geocode.js, we either provide one argument for an error, or we provide the
second argument if things went well. Instead of doing that though, promises give
us two functions we can call.
Now, in order to illustrate exactly how we can use these, we'll call resolve. Once
again, this is not asynchronous. We're not doing anything quite yet. So all of this
will happen essentially in real time, as far as you see in Terminal. We'll call